// 670. 最大交换
/**
 * @param {number} num
 * @return {number}
 */
// 暴力
var maximumSwap = function (num) {
	const arr = (num + '').split('')
	const n = arr.length
	let maxNumber = num
	for (let i = 0; i < n; i++) {
		for (let j = i + 1; j < arr.length; j++) {
			swap(arr, i, j)
			maxNumber = Math.max(maxNumber, +arr.join(''))
			// 复原
			swap(arr, i, j)
		}
	}
	return maxNumber
}
const swap = (arr, i, j) => {
	const temp = arr[i]
	arr[i] = arr[j]
	arr[j] = temp
}
// 贪心
var maximumSwap = (num) => {
	const arr = (num + '').split('')
	const n = arr.length
	let maxIdx = n - 1
	let idx1 = -1,
		idx2 = -1

	for (let i = n - 1; i >= 0; i--) {
		if (arr[i] > arr[maxIdx]) {
			maxIdx = i
		} else if (arr[i] < arr[maxIdx]) {
			idx1 = i
			idx2 = maxIdx
		}
	}
	if (idx1 >= 0) {
		swap(arr, idx1, idx2)
		return +arr.join('')
	}
	return num
}
const result = maximumSwap(2736)
console.log('maximumSwap :>>', result)
